import { useReducer } from 'react'

/*
  纯函数
  1.不能执行带副作用的(包括:ajax请求,打开数据库, console.log)
  2.返回值里不能有类似于Math.random()或Date.now()
  3.它不能改变参数或环境里的变量值

  useReducer使用场景
  - 一个状态它的改变由多种不同的方式触发
  - 这个状态的值需要在上一次状态基础上修改
  useReducer参数
  ```
  useReducer(render, initialValue[,initFunc]) // 返回[state,dispatch]
  ```
  ## reducer 是纯函数

  ```js
  const reducer = (state,action) =>{
    // action 是一个object, {type:'动作类型',payload: {...自定义内容}} // payload 荷载
    // {type: 'add_user',payload:{username,password}}
    // {type: 'remove_user,payload: userId}
    // state = []
    switch(action.type) {
      case 'add_user':
        return [...state,action.payload]
      case 'remove_user':
        return state.filter(user=>user.userId !== action.payload)
      default :
        return state
    }
  }
  ```
  
*/
const reducer = (state, action) => {
  const { type } = action
  switch (type) {
    case 'Incr':
      return { count: state.count + 1 } // nextState
    case 'Decr':
      return { count: state.count - 1 } // nextState
    case 'IncrAmount':
      return { count: state.count + action.amout } // nextState
    default:
      return state
  }
}

const ReducerDemo = () => {
  const [state, dispatch] = useReducer(reducer, { count: 0 })
  return (
    <>
      <h2>useReducer例子</h2>
      计数器: {state.count}
      <button onClick={() => dispatch({ type: 'Incr' })}>incr</button>
      <button onClick={() => dispatch({ type: 'Decr' })}>incr</button>
      <button onClick={() => dispatch({ type: 'IncrAmount', amout: 2 })}>incr 2</button>
    </>
  )
}

export default ReducerDemo
